#include <QColorDialog>
#include <QMouseEvent>
#include <QPainter>
#include "ItemColor.h"

QWidget *ItemColor::createWidget(WidgetStyle s)
{
    auto w = new ColorPicker;
    connect(w, &ColorPicker::colorPicked, this, &ItemColor::onWidgetEditedWrapper);
    return w;
}

void ItemColor::update(QWidget *widget, UpdateOption option)
{
    ColorPicker *picker = qobject_cast<ColorPicker*>(widget);
    if (picker != nullptr)
    {
        if (option == UpdateOption::WidgetContent)
        {
            picker->setColor(m_data);
        }
        else if (option == UpdateOption::Item)
        {
            this->m_data = picker->getColor();
            qInfo() << "update: " << this->m_data;
        }
    }
    else
    {
        qWarning() << "";
    }
}

void ItemColor::writeToData(QDataStream &stream) const
{
    stream << m_data;
}

void ItemColor::readFromData(QDataStream &stream)
{
    stream >> m_data;
    emit itemEdited();
}



void ColorPicker::pickColor()
{
    QColor color = QColorDialog::getColor();
    if (color.isValid())
    {
        m_color = color;
        emit colorPicked(color);
        update();
    }
}

void ColorPicker::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    if (mouseOnColor)
        painter.setPen(QPen(Qt::blue, 2));
    else
        painter.setPen(Qt::NoPen);
    painter.setBrush(m_color);
    painter.drawEllipse(QPoint(15, height() / 2), 10, 10);
    painter.setPen(QPen(Qt::black, 2));
    painter.drawText(30, 0, width() - 30, height(), Qt::AlignLeft | Qt::AlignVCenter, "#" + QString::number(m_color.rgb(), 16).toUpper());

}


void ColorPicker::mouseReleaseEvent(QMouseEvent *)
{
    pickColor();
}
